package http.thread;

import com.google.common.util.concurrent.*;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * 任务的执行工厂
 */
public class ExecutorFactor {
    /*固定线程池数量*/
    private static ListeningExecutorService EXECUTOR_SERVICE = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());


    public static void exec(final FutureService objService, final Object... args) {
        // 异步处理
        ListenableFuture<Object> future = EXECUTOR_SERVICE.submit(
                new Callable<Object>() {
                    public Object call() throws Exception {
                        Object o = objService.handler(args);
                        return o;
                    }
                });


        Futures.addCallback(future,new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object o) {
                // TODO 成功处理
                objService.onSuccess(o, args);
            }

            @Override
            public void onFailure(Throwable throwable) {
                // TODO 失败处理
                objService.onFailure(throwable, args);
            }
        },EXECUTOR_SERVICE);
    }
}
